import $store from '@/store/index.js';
import msgSqlite from "@/sqlite_services/msg.js";

// 私聊消息处理函数
const handle = async(data) => {
    try {
        let msgList = data.content_texts;
        if (msgList.length === 0) return;

        // 提取所有消息ID和本地ID，并确保每个ID都是字符串格式
        let ids = msgList.flatMap(item => [`${item.msg_id}`, `${item.local_id}`].filter(id => id && id != '0'));
		// 为每个ID添加引号，以便在SQL查询中正确处理
		let quotedIds = ids.map(id => `"${id}"`).join(',');
         // 批量查询现有消息
        let existingMessages = await $store.state.user.sqlite.message.where([
            { field: 'msg_id', val: `(${quotedIds})`, opt: 'IN' }
        ]).get();
		// 使用Set存储已存在的消息ID
        let existingMsgIds = new Set(existingMessages.map(msg => msg.msg_id));

        // 筛选需要插入的新消息
        let newMessages = msgList.filter(item => 
            !existingMsgIds.has(item.msg_id) && !existingMsgIds.has(item.local_id)
        ).map(item => ({
            msg_id: item.msg_id,
            local_id: (item.local_id && item.local_id != '0') ? item.local_id : item.msg_id,
            sender_id: item.sender_id,
            target_id: item.target_id,
            create_time: item.create_time,
            msg_type: item.msg_type,
            conversation_id: item.conversation_id,
            chat_type: item.chat_type,
            msg_status: 'unread',
            content_text: item.content_text
        }));

        if (newMessages.length > 0) {
            await msgSqlite.newMsg(newMessages, true);
        }
    } catch (e) {
        console.error(e);
    }
};

export default handle;
